package com.robam.cloud.component.componentfeign.realcheck.aop;

import com.robam.cloud.common.bean.common.Constant;
import com.robam.cloud.common.bean.restful.entity.RespMsg;
import com.robam.cloud.common.bean.restful.entity.ServiceException;
import com.robam.cloud.common.util.StringUtil;
import com.robam.cloud.component.componentfeign.basefeign.FeignUserCenterBaseUtil;
import com.robam.cloud.component.componentfeign.realcheck.annotation.CheckRealUser;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Aspect
@Slf4j
public class AnnotationCheckRealUserAspect {
    @Autowired
    FeignUserCenterBaseUtil feignUserCenterUtilBase;
    @Autowired
    RedisTemplate redisTemplate;


    @Pointcut("@annotation(checkRealUser)")
    public void pointCut(CheckRealUser checkRealUser) {
    }

    @Around("pointCut(checkRealUser)")
    public Object around(ProceedingJoinPoint pjp, CheckRealUser checkRealUser) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        String token = request.getHeader(Constant.TOKENNAME);
        if (token == null) {
            throw new ServiceException("未携带有效token");
        }
        String accountId = String.valueOf(redisTemplate.opsForValue().get(Constant.TOKENNAME + ":" + token));
        if (StringUtil.isEmpty(accountId)) {
            response.setStatus(RespMsg.RESULT_CODE_401);
            throw new ServiceException("token过期请重新登录");
        }

        RespMsg respMsg = feignUserCenterUtilBase.realVerify(Long.parseLong(accountId));
        if (respMsg == null) {
            throw new ServiceException("用户中心服务异常请稍后重试");
        }
        if (respMsg.getCode() != 200) {
            throw new ServiceException(respMsg.getMsg());
        }
        boolean flag = (Boolean) respMsg.getData();
        if (!flag) {
            response.setStatus(RespMsg.RESULT_CODE_402);
            throw new ServiceException("用户未实名请先实名");
        }
        Object result;
        result = pjp.proceed();
        return result;
    }
}
